package com.bjpowernode.listener;

import com.bjpowernode.tools.My;
import com.mysql.cj.jdbc.AbandonedConnectionCleanupThread;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;


//ServletContext对象其实就是Tomcat服务对象，一个Tomcat服务对象服务则只有一个ServletContext对象
//ServletContext对象是在Tomcat服务启动的时候由Tomcat自己实例化

//ServletContextListener监听Tomcat服务的启动与关闭
//可以使用<context-param>注册一些参数，然后提供给ServletContext对象
//在我们自定的ServletContextListener的里面可以很容易的获取ServletContext对象
//控制器中可以使用请求对象获取ServletContext对象，ServletContext servletContext = res.getServletContext();

//如果在其它的层面（业务层，beans层）想要使用ServletContext的全局参数（<context-param>），则需要由控制器传递即可，不要在（业务层，beans层）想办法拿到请求对象或者ServletContext对象

public class MyServletContextListener implements ServletContextListener {
    //Tomcat启动的时候执行
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("contextInitialized.................");
        ServletContext servletContext = sce.getServletContext();
        String a = servletContext.getInitParameter("a");
        String b = servletContext.getInitParameter("b");
        String contextConfigLocation = servletContext.getInitParameter("contextConfigLocation");
        System.out.println("a.................:" + a);
        System.out.println("b.................:" + b);
        System.out.println("contextConfigLocation.................:" + contextConfigLocation);

//        My.context = sce.getServletContext();
    }

    //Tomcat关闭的时候执行
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("contextDestroyed.................");
        //这里如果Web应用拥有多个数据库的连接，可以一并关闭
        //java.sql.Driver;
        Enumeration<Driver> drivers = DriverManager.getDrivers();
        Driver driver = null;
        while (drivers.hasMoreElements()) {
            try {
                driver = drivers.nextElement();
                DriverManager.deregisterDriver(driver);
            } catch (SQLException ex) {
            }
        }
        //mysql驱动官方提供的关闭方案
        AbandonedConnectionCleanupThread.checkedShutdown();
    }
}
